Skip to main content

React : Building a Multi-Page React Application with .NET Web API Integration using HTTP Interceptors

 

In this blog post, we'll explore how to create a multi-page React application that communicates with a .NET Web API backend. We'll leverage HTTP interceptors in React to handle API requests and responses, allowing seamless integration between the frontend and backend. Additionally, we'll design the application to support dynamic pages, making it easy to add new features in the future.

Step 1: Set Up the .NET Web API: Begin by creating a .NET Web API project to serve as the backend for our React application. Define endpoints to handle various CRUD operations or any other functionality required by the frontend.

Step 2: Create React Application: Generate a new React application using Create React App. This will set up the basic structure and dependencies for our frontend.

npx create-react-app my-react-app
cd my-react-app
Step 3: Implement HTTP Interceptors in React: Create a custom HTTP interceptor in React to intercept API requests and responses. This allows us to add headers, handle authentication, or perform error handling globally.
// httpInterceptor.js
import axios from 'axios';

axios.interceptors.request.use(
  (config) => {
    // Add authentication token or other headers if needed
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  (response) => {
    // Handle successful response
    return response;
  },
  (error) => {
    // Handle error response
    return Promise.reject(error);
  }
);

export default axios;
Step 4: Create Pages and Components: Design your React application with multiple pages and reusable components. Each page should correspond to a specific feature or functionality of your application.
// HomePage.js
import React from 'react';

const HomePage = () => {
  return (
    <div>
      <h1>Welcome to My React App</h1>
      <p>This is the home page of our application.</p>
    </div>
  );
}

export default HomePage;
Step 5: Implement Routing: Set up routing in your React application using React Router. Define routes for each page and handle navigation between them.
// App.js
import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import HomePage from './pages/HomePage';
// Import other pages

const App = () => {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={HomePage} />
        {/* Define routes for other pages */}
      </Switch>
    </Router>
  );
}

export default App;
Let's add two more pages to our React application and adjust the code snippets accordingly.
Create Additional Pages: Create two more pages in your React application to demonstrate multiple pages. For example, let's create a "AboutPage.js" and "ContactPage.js".
// AboutPage.js
import React from 'react';

const AboutPage = () => {
  return (
    <div>
      <h1>About Us</h1>
      <p>This is the About page of our application.</p>
    </div>
  );
}

export default AboutPage;
// ContactPage.js
import React from 'react';

const ContactPage = () => {
  return (
    <div>
      <h1>Contact Us</h1>
      <p>This is the Contact page of our application.</p>
    </div>
  );
}

export default ContactPage;
Update Routing: Adjust the routing in your React application to include the new pages.
// App.js
import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import HomePage from './pages/HomePage';
import AboutPage from './pages/AboutPage'; // New page
import ContactPage from './pages/ContactPage'; // New page

const App = () => {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={HomePage} />
        <Route exact path="/about" component={AboutPage} /> {/* New route */}
        <Route exact path="/contact" component={ContactPage} /> {/* New route */}
      </Switch>
    </Router>
  );
}

export default App;
Update Navigation: Update the navigation menu or links in your application to navigate between the pages.
// Navigation.js
import React from 'react';
import { Link } from 'react-router-dom';

const Navigation = () => {
  return (
    <nav>
      <ul>
        <li><Link to="/">Home</Link></li>
        <li><Link to="/about">About</Link></li>
        <li><Link to="/contact">Contact</Link></li>
      </ul>
    </nav>
  );
}

export default Navigation;
With these changes, your React application now includes multiple pages (Home, About, and Contact), each with its own route and corresponding component. Users can navigate between these pages using the navigation menu or links. This setup allows for a more dynamic and engaging user experience in your web application.

Step 6: Make API Calls: Integrate API calls into your React components to fetch data from the backend. Use the custom HTTP interceptor we created earlier to handle API requests.
// ExampleComponent.js
import React, { useEffect, useState } from 'react';
import httpInterceptor from '../httpInterceptor';

const ExampleComponent = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    httpInterceptor.get('/api/data')
      .then(response => {
        setData(response.data);
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  }, []);

  return (
    <div>
      {data ? (
        <p>Data: {data}</p>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
}

export default ExampleComponent;
Conclusion: By following the steps outlined in this blog post, you can create a multi-page React application that communicates with a .NET Web API backend using HTTP interceptors. This setup allows for efficient API integration, dynamic page navigation, and easy addition of new features in the future. With React's component-based architecture and .NET Web API's robust backend capabilities, you can build powerful and scalable web applications.

Comments

Popular posts from this blog

Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API

RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer). 1. Prerequisites Install RabbitMQ locally or on a server. Default Management UI: http://localhost:15672 Default Credentials: guest/guest Install the RabbitMQ.Client package for .NET: dotnet add package RabbitMQ.Client 2. Architecture Overview Shopping Cart API (Producer): Sends a message when a user places an order. RabbitMQ : Acts as the broker to hold the message. Order API (Consumer): Receives the message and processes the order. 3. RabbitMQ Producer: Shopping Cart API Step 1: Install RabbitMQ.Client Ensure the RabbitMQ client library is installed: dotnet add package RabbitMQ.Client Step 2: Create the Producer Service Add a RabbitMQProducer class to send messages. RabbitMQProducer.cs : using RabbitMQ.Client; usin...

.NET 10: Your Ultimate Guide to the Coolest New Features (with Real-World Goodies!)

 Hey .NET warriors! 🤓 Are you ready to explore the latest and greatest features that .NET 10 and C# 14 bring to the table? Whether you're a seasoned developer or just starting out, this guide will show you how .NET 10 makes your apps faster, safer, and more productive — with real-world examples to boot! So grab your coffee ☕️ and let’s dive into the awesome . 💪 1️⃣ JIT Compiler Superpowers — Lightning-Fast Apps .NET 10 is all about speed . The Just-In-Time (JIT) compiler has been turbocharged with: Stack Allocation for Small Arrays 🗂️ Think fewer heap allocations, less garbage collection, and blazing-fast performance . Better Code Layout 🔥 Hot code paths are now smarter, meaning faster method calls and fewer CPU cache misses. 💡 Why you care: Your APIs, desktop apps, and services now respond quicker — giving users a snappy experience . 2️⃣ Say Hello to C# 14 — More Power in Your Syntax .NET 10 ships with C# 14 , and it’s packed with developer goodies: Field-Bac...

Optional Parameters in C# — Writing Flexible and Clean Methods

Hello, .NET developers! 👋 How often have you created multiple method overloads just to handle slightly different cases? Maybe one method accepts two parameters, another three, and one more adds a flag for debugging? That’s a lot of code duplication for something that can be solved beautifully with optional parameters . Optional parameters in C# let you define default values for method arguments. When a caller doesn’t pass a value, the compiler automatically substitutes the default. This feature helps keep your APIs simple, readable, and maintainable. 🎥 Explore more on YouTube : DotNet Full Stack Dev Understanding Optional Parameters Optional parameters are defined by assigning default values in the method signature. When calling the method, you can omit those parameters if you’re okay with the defaults. Example public class Logger { public void Log(string message, string level = "INFO", bool writeToFile = false) ...